import express from 'express';
import cors from 'cors';
import multer from 'multer';
import winston from 'winston';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import FormData from 'form-data';
import axios from 'axios';

// 配置日志
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [new winston.transports.Console()]
});

const app = express();

// 中间件
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = 'uploads';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024 // 50MB
  },
  fileFilter: function (req, file, cb) {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/dcm', 'image/bmp'];
    const allowedExtensions = ['.jpg', '.jpeg', '.png', '.dcm', '.dicom', '.bmp', '.dib'];

    // 检查MIME类型
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    }
    // 检查文件扩展名（处理BMP等可能被错误识别的文件）
    else if (allowedExtensions.some(ext => file.originalname.toLowerCase().endsWith(ext))) {
      cb(null, true);
    } else {
      cb(new Error(`不支持的文件类型: ${file.mimetype}。支持的格式: JPG, PNG, DICOM, BMP`));
    }
  }
});

// 模拟用户数据
const users = {
  admin: {
    id: 1,
    username: 'admin',
    password: 'Admin123',
    real_name: '系统管理员',
    role: 3,
    department: '信息科',
    title: '系统管理员'
  }
};

// 模拟JWT
const createToken = (user) => {
  return 'mock_token_' + user.id + '_' + Date.now();
};

// AI服务地址
const AI_SERVICE_URL = 'http://localhost:5001';

// 请求日志
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.path}`);
  next();
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'API运行正常',
    data: {
      timestamp: new Date().toISOString(),
      ai_service_url: AI_SERVICE_URL
    }
  });
});

// 登录
app.post('/api/doctors/login', (req, res) => {
  const { username, password } = req.body;

  logger.info('登录请求:', { username, password });

  if (!username || !password) {
    return res.status(400).json({
      success: false,
      message: '用户名和密码不能为空'
    });
  }

  const user = users[username];
  if (!user || user.password !== password) {
    return res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    });
  }

  const token = createToken(user);
  res.json({
    success: true,
    message: '登录成功',
    data: {
      token,
      doctor: {
        doctor_id: user.id,
        username: user.username,
        real_name: user.real_name,
        role: user.role,
        department: user.department,
        title: user.title,
        role_name: user.role === 3 ? '系统管理员' : '医生'
      }
    }
  });
});

// 获取用户信息
app.post('/api/doctors/info', (req, res) => {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token || !token.startsWith('mock_token_')) {
    return res.status(401).json({
      success: false,
      message: '无效的令牌'
    });
  }

  // 从token中提取用户ID
  const userId = parseInt(token.split('_')[2]);
  const user = Object.values(users).find(u => u.id === userId);

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在'
    });
  }

  res.json({
    success: true,
    message: '获取用户信息成功',
    data: {
      doctor_id: user.id,
      username: user.username,
      real_name: user.real_name,
      role: user.role,
      department: user.department,
      title: user.title,
      role_name: user.role === 3 ? '系统管理员' : '医生'
    }
  });
});

// 任务提交（支持真实文件上传）
let taskIdCounter = 1;
app.post('/api/scoring/submit', upload.single('image'), async (req, res) => {
  try {
    const { patient_code, clinical_text } = req.body;
    const imageFile = req.file;

    logger.info('收到任务提交请求:', {
      patient_code,
      clinical_text: clinical_text?.substring(0, 100),
      hasImage: !!imageFile
    });

    // 参数验证
    if (!imageFile) {
      return res.status(400).json({
        success: false,
        message: '请上传内镜图像'
      });
    }

    if (!patient_code || !patient_code.trim()) {
      return res.status(400).json({
        success: false,
        message: '患者编号不能为空'
      });
    }

    const taskId = taskIdCounter++;

    logger.info(`任务 ${taskId} 提交成功，文件: ${imageFile.filename}`);

    // 立即调用AI服务进行分析
    try {
      logger.info('调用AI服务进行分析...');

      // 创建FormData发送给AI服务
      const formData = new FormData();
      formData.append('image_file', fs.createReadStream(imageFile.path), {
        filename: imageFile.originalname,
        contentType: imageFile.mimetype
      });

      const aiResponse = await axios.post(`${AI_SERVICE_URL}/v1/predict`, formData, {
        headers: {
          ...formData.getHeaders(),
          'Content-Type': 'multipart/form-data'
        },
        timeout: 30000 // 30秒超时
      });

      logger.info('AI服务响应:', aiResponse.data);

      if (aiResponse.data.success) {
        const aiResult = aiResponse.data.data;

        // 直接返回AI分析结果
        res.json({
          success: true,
          message: 'AI分析完成',
          data: {
            task_id: taskId,
            patient_code,
            status: 3, // 已完成
            ai_result: {
              score: aiResult.uceis_score || aiResult.score,
              severity_name: aiResult.severity,
              severity_code: aiResult.severity_code,
              confidence: Math.round((aiResult.confidence || 0.85) * 100),
              analysis_details: aiResult.analysis_details,
              model_version: aiResult.model_version,
              processing_time_ms: aiResult.processing_time_ms,
              image_info: aiResult.image_info,
              note: "使用真实UCEIS评分模型"
            },
            created_at: new Date().toISOString(),
            completed_at: new Date().toISOString()
          }
        });

        // 保存任务结果以供后续查询
        const taskResult = {
          task_info: {
            task_id: taskId,
            patient_code,
            status: 3, // 已完成
            created_at: new Date().toISOString(),
            completed_at: new Date().toISOString()
          },
          ai_result: {
            score: aiResult.uceis_score || aiResult.score,
            severity_name: aiResult.severity,
            severity_code: aiResult.severity_code,
            confidence: Math.round((aiResult.confidence || 0.85) * 100),
            analysis_details: aiResult.analysis_details,
            model_version: aiResult.model_version,
            processing_time_ms: aiResult.processing_time_ms,
            image_info: aiResult.image_info,
            note: "使用真实UCEIS评分模型"
          }
        };
        taskResults.set(taskId, taskResult);

        // 清理临时文件
        try {
          fs.unlinkSync(imageFile.path);
          logger.info('清理临时文件:', imageFile.path);
        } catch (cleanupError) {
          logger.warn('清理临时文件失败:', cleanupError.message);
        }

      } else {
        throw new Error(aiResponse.data.message || 'AI分析失败');
      }

    } catch (aiError) {
      logger.error('AI服务调用失败:', aiError.message);

      // 清理临时文件
      try {
        fs.unlinkSync(imageFile.path);
      } catch (cleanupError) {
        logger.warn('清理临时文件失败:', cleanupError.message);
      }

      // 判断是否是真实模型连接问题
      const isRealModelUnavailable = aiError.code === 'ECONNREFUSED' ||
                                     aiError.code === 'ETIMEDOUT' ||
                                     aiError.message.includes('ECONNREFUSED') ||
                                     aiError.message.includes('ETIMEDOUT');

      if (isRealModelUnavailable) {
        // 如果真实模型不可用，明确显示
        res.status(500).json({
          success: false,
          message: '真实AI模型未启动或不可用',
          error: 'MODEL_NOT_AVAILABLE',
          details: '请确保真实AI模型服务正在运行 (端口5001)',
          isRealModel: false
        });
      } else {
        // 其他AI服务错误
        res.status(500).json({
          success: false,
          message: 'AI分析失败: ' + aiError.message,
          error: 'AI_SERVICE_ERROR',
          isRealModel: true
        });
      }
    }

  } catch (error) {
    logger.error('任务提交失败:', error);

    // 清理临时文件
    if (req.file) {
      try {
        fs.unlinkSync(req.file.path);
      } catch (cleanupError) {
        logger.warn('清理临时文件失败:', cleanupError.message);
      }
    }

    res.status(500).json({
      success: false,
      message: '任务提交失败: ' + error.message
    });
  }
});

// 任务列表
app.post('/api/scoring/list', (req, res) => {
  const { page = 1, limit = 10, status = null } = req.body;

  const mockTasks = [];
  const statusNames = { 1: '待处理', 2: '分析中', 3: '已完成', 4: '失败' };
  for (let i = 1; i <= 5; i++) {
    const status = Math.floor(Math.random() * 4) + 1;
    mockTasks.push({
      task_id: i,
      patient_code: `TEST${String(i).padStart(3, '0')}`,
      doctor_name: '测试医生',
      department: '消化内科',
      status: status,
      status_name: statusNames[status],
      score: status === 3 ? Math.floor(Math.random() * 13) : null,
      severity_name: status === 3 ? ['缓解期', '轻度', '中度', '重度'][Math.floor(Math.random() * 4)] : null,
      created_at: new Date(Date.now() - i * 86400000).toISOString(),
      completed_at: i <= 2 ? new Date(Date.now() - i * 86400000 + 3600000).toISOString() : null
    });
  }

  res.json({
    success: true,
    message: '获取任务列表成功',
    data: {
      items: mockTasks,
      pagination: {
        current_page: parseInt(page),
        page_size: parseInt(limit),
        total: mockTasks.length,
        total_pages: Math.ceil(mockTasks.length / limit)
      }
    }
  });
});

// 任务结果查询
const taskResults = new Map();
app.post('/api/scoring/result', (req, res) => {
  const { task_id } = req.body;

  let result = taskResults.get(task_id);

  if (!result) {
    // 首次查询，返回初始状态
    result = {
      task_info: {
        task_id,
        patient_code: 'UNKNOWN',
        status: 2, // 分析中
        created_at: new Date().toISOString()
      },
      ai_result: null
    };
    taskResults.set(task_id, result);
  }

  res.json({
    success: true,
    message: '获取任务结果成功',
    data: result
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(413).json({
        success: false,
        message: '文件过大，最大允许50MB'
      });
    }
    if (error.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({
        success: false,
        message: '文件数量超过限制'
      });
    }
  }

  logger.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误: ' + error.message
  });
});

// 启动服务器
const PORT = 4000;
app.listen(PORT, () => {
  logger.info(`🚀 集成AI模型的服务器启动成功! 端口: ${PORT}`);
  logger.info(`📝 测试账号: admin / Admin123`);
  logger.info(`🤖 AI服务地址: ${AI_SERVICE_URL}`);
  logger.info(`📁 文件上传目录: uploads/`);
});

export default app;